{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import sys\n",
    "import pprint\n",
    "\n",
    "input_description_file = \"../../image_caption_data/results_20130124.token\"\n",
    "output_vocab_file = \"../../image_caption_data/vocab.txt\"\n",
    "\n",
    "\n",
    "def count_vocab(input_token_filename):\n",
    "    with open(input_token_filename, 'r') as f:\n",
    "        lines = f.readlines()\n",
    "    \n",
    "    max_length_of_sentences = 0\n",
    "    length_dict = {}\n",
    "    vocab_dict = {}\n",
    "    \n",
    "    for line in lines:\n",
    "        image_id, description = line.strip('\\n').split('\\t')\n",
    "        words = description.strip(' ').split()\n",
    "        max_length_of_sentences = max(max_length_of_sentences, len(words))\n",
    "        length_dict.setdefault(len(words), 0)\n",
    "        length_dict[len(words)] += 1\n",
    "\n",
    "        for word in words:\n",
    "            vocab_dict.setdefault(word, 0)\n",
    "            vocab_dict[word] += 1\n",
    "    \n",
    "    print max_length_of_sentences\n",
    "    pprint.pprint(length_dict)\n",
    "    return vocab_dict\n",
    "\n",
    "vocab_dict = count_vocab(input_description_file)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sorted_vocab_dict = sorted(vocab_dict.items(), key = lambda d:d[1], reverse=True)\n",
    "with open(output_vocab_file, 'w') as f:\n",
    "    f.write(\"<UNK>\\t100000\\n\")\n",
    "    for item in sorted_vocab_dict:\n",
    "        f.write('%s\\t%d\\n' % item)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
